from module.aaa_example import example
from flask import render_template, request, Response, redirect, url_for,jsonify
import asyncio

@example.route("/")
def index():
    return render_template("/aaa_example/index.html")

def mu_ban():
    list1=["1","2"]
    return render_template("/aaa_example/mu_ban/mu_ban.html",mu_bans=list1,age=18)
# 相当于@example.route("/mu_ban")
example.add_url_rule("/mu_ban",view_func=mu_ban)

@example.route("/asnyc_demo")
async def async_demo():
    print("asnyc_demo1")
    await asyncio.sleep(3)
    # time.sleep(5)
    print("asnyc_demo2")
    return "asnyc_demo"

@example.route("/web_socket_demo")
def web_socket_demo():
    return render_template("/aaa_example/web_socket.html")

@example.route("/get")
def example_get():
    if request.method == "GET":
        arg1 = request.args.get("arg1")
        arg2 = request.args.get("arg1")
        return "GET 参数1:{} 参数2:{}".format(arg1, arg2)
    # 返回一个自己创建的Response
    body = "get 失败"
    r1 = Response(body)
    # r1.headers["Content-Type"]="text/event-stream"
    return r1


@example.route("/post", methods=["POST", "GET"])
def example_post():
    if request.method == "POST":
        if request.content_type.startswith("application/json"):
            # arg1 = request.get_json()["arg1"]
            arg1 = request.json.get("arg1")
            arg2 = request.json.get("arg2")
            return jsonify({"type:":"application/json","arg1":arg1,"arg2":arg2})
        elif request.content_type.startswith("multipart/form-data"):
            arg1 = request.form.get("arg1")
            arg2 = request.form.get("arg2")
            return jsonify({"type:":"multipart/form-data","arg1":arg1,"arg2":arg2})
        elif request.content_type.startswith("application/x-www-form-urlencoded"):
            arg1 = request.values.get("arg1")
            arg2 = request.values.get("arg2")
            return jsonify({"type:":"application/x-www-form-urlencoded","arg1":arg1,"arg2":arg2})
        else:
            data = request.get_data().decode("utf8")
            return "post get_data:{}".format(data)
    return redirect('/example/')


# 参数类型 string int float
# 在url中传入参数时，如果没有指定参数的类型，会默认为参数是string类型。
@example.route("/url_hou_zui/<string:file_content>", methods=["POST", "GET"])
def example_arg(file_content):
    # 把前端传送过来的内容包装成文件再传给前端下载
    r1 = Response(file_content.encode("utf8"))
    # 设置下载文件的响应头
    r1.headers["Content-Disposition"] = "attachment;filename=down_example.txt"
    r1.headers["Content-Type"] = "application/octet-stream"
    return r1

@example.route('/redirect')
def example_redirect():
    # 访问静态文件 url_for('static', filename='style.css')
    # 这个文件应该存储在文件系统上的 static/style.css 
    # url重定向到example的index函数
    return redirect(url_for("example.index"))

